using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Terminal.Advanced_AEUC_settings_controls.Settings_AUX;
using Terminal.Advanced_AEUC_settings_controls.Settings_Interfaces;
using Terminal.Advanced_AEUC_settings_controls.Settings_Editing_Forms;
using Terminal.Advanced_AEUC_settings_controls.Setting_Advanced_Control;
using System.IO;
using CommLink;
using System.Reflection;
using System.Threading;

namespace Terminal.Advanced_AEUC_settings_controls.Advanced_controls
{
    /// <summary>
    /// Holds AEUCTabbedParentControl and a corresponding AEUCPanelInfoControl. Handles user interaction.
    /// </summary>
    public partial class UCTabPage : UserControl
    {
        /// <summary>
        /// Communication module reference.
        /// </summary>
        CommLink.CommLink commLink;

        #region UI elemetns
        #region Specialized user interface controls
        AEUCTabbedParentControl atpc;
        AEUCPanelInfoControl pic;
        #endregion
        #region Buttons
        Button btnTransf;
        Button btnUpdate;
        Button btnApply;
        Button btnConnect;
        #endregion
        #endregion
        /// <summary>
        /// Public contructor
        /// </summary>
        public UCTabPage()
        {
            InitializeComponent();

            atpc = new AEUCTabbedParentControl(new CommLink.CommLink.MessageSend(bytestreamTransfer));
            atpc.OnAEUCControlsUpdated += new AEUCTabbedParentControl.AEUCControlsUpdated(atpc_OnAEUCControlsUpdated);
            atpc.Location = new System.Drawing.Point(3, 3);
            atpc.Parent = this;

            pic = new AEUCPanelInfoControl(atpc);
            pic.Location = new System.Drawing.Point(Size.Width - pic.Width - 5, 3);
            pic.Parent = this;

            atpc.Size = new System.Drawing.Size(Size.Width - pic.Width, Size.Height - 20);

            btnTransf = new Button();
            btnUpdate = new Button();
            btnApply = new Button();
            btnConnect = new Button();

            btnTransf.Size = new Size(btnTransf.Size.Width*2, btnTransf.Size.Height);
            btnUpdate.Size = btnTransf.Size;

            btnTransf.Text = "Transfer param struct";
            btnUpdate.Text = "Update param struct";
            btnApply.Text = "Apply Page";
            btnApply.Visible = false;
            btnConnect.Text = "Connect";
            btnConnect.Visible = false;

            btnApply.Location = new Point(pic.Location.X + pic.Size.Width - btnApply.Size.Width, pic.Location.Y + pic.Size.Height + 5);
            btnTransf.Location = new Point(pic.Location.X + pic.Size.Width - btnTransf.Size.Width /*- 3 - btnApply.Size.Width*/, pic.Location.Y + pic.Size.Height + 5);
            btnUpdate.Location = new Point(btnTransf.Location.X, btnTransf.Location.Y + btnTransf.Size.Height + 2);
            btnConnect.Location = new Point(btnApply.Location.X, btnUpdate.Location.Y + btnApply.Size.Height + 2);

            btnTransf.Parent = this;
            btnUpdate.Parent = this;
            btnApply.Parent = this;
            btnConnect.Parent = this;

            btnTransf.Click += new EventHandler(btnTransf_Click);
            btnUpdate.Click += new EventHandler(btnUpdate_Click);
            btnApply.Click += new EventHandler(btnApply_Click);
            //btnConnect.Click += new EventHandler(btnConnect_Click);
        }

        /// <summary>
        /// Delegate invoked when underlying controls update
        /// </summary>
        public delegate void UCInternControlsUpdated();
        /// <summary>
        /// Event fired when when underlying controls update
        /// </summary>
        public event UCInternControlsUpdated OnUCInternControlsUpdated;

        void atpc_OnAEUCControlsUpdated()
        {
            if (OnUCInternControlsUpdated != null)
                OnUCInternControlsUpdated();
        }
        /// <summary>
        /// Overrided OnSizeChabged method
        /// </summary>
        /// <param name="e">Event arguments</param>
        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);

            if (pic != null && atpc != null)
            {
                pic.Location = new System.Drawing.Point(Size.Width - pic.Width - 5, 3);
                atpc.Size = new System.Drawing.Size(Size.Width - pic.Width - 10, Size.Height - 5);

                btnApply.Location = new Point(pic.Location.X + pic.Size.Width - btnApply.Size.Width, pic.Location.Y + pic.Size.Height + 5);
                btnTransf.Location = new Point(pic.Location.X + pic.Size.Width - btnTransf.Size.Width /*- 3 - btnApply.Size.Width*/, pic.Location.Y + pic.Size.Height + 5);
                btnUpdate.Location = new Point(btnTransf.Location.X, btnTransf.Location.Y + btnTransf.Size.Height + 2);
                btnConnect.Location = new Point(btnApply.Location.X, btnUpdate.Location.Y + btnApply.Size.Height + 2);
            }
        }

        #region Buttons and UI elemets of the User-Control tab page control
        void btnApply_Click(object sender, EventArgs e)
        {
        }

        void btnUpdate_Click(object sender, EventArgs e)
        {
            send_omx_sett_read_request_msg();
        }

        void btnTransf_Click(object sender, EventArgs e)
        {
            paramsStructureSettingsTransfer();
        }

        void btnConnect_Click(object sender, EventArgs e)
        {
        }
        #endregion

        #region UI Tab page, page properties and UI save/load public interface
        /// <summary>
        /// Add a new OMX param page with specified name.
        /// </summary>
        /// <param name="iname">Name of the OMX param page</param>
        /// <returns>Index in the tab page collection of the new tab page</returns>
        public int AddOMXParamPage(string iname)
        {
            return atpc.AddTabPage(iname);
        }

        /// <summary>
        /// Remove selected OMX param tab page
        /// </summary>
        /// <param name="idx">Selected tab page index</param>
        public void RemOMXParamPage(int idx)
        {
            atpc.RemTabPage(idx);
        }

        /// <summary>
        /// Returns the top corner point of a tab page
        /// </summary>
        /// <param name="idx">Index of the selected tab page</param>
        /// <returns>Top corner point</returns>
        public Point tabPageLocation(int idx)
        {
            return new Point(atpc.TabPages[idx].Top, atpc.TabPages[idx].Left);
        }

        /// <summary>
        /// Returns the title a tab page
        /// </summary>
        /// <param name="idx">Index of the selected tab page</param>
        /// <returns>Title of the tab page</returns>
        public string tabPageTitle(int idx)
        {
            return atpc.TabPages[idx].Text;
        }

        /// <summary>
        /// Open OMX param properties for selected tab page.
        /// </summary>
        /// <param name="idx">Selected tab page index</param>
        public void GetOMXParamPageProps(int idx)
        {
            atpc.OMXStructPageProperties(idx);
        }

        /// <summary>
        /// Open OMX component messaging menu.
        /// </summary>
        public void GetOMXComponentMessaging()
        {
            atpc.OMXSCompMessagingProperties();
        }

        /// <summary>
        /// Renames an OMX param properties tab page.
        /// </summary>
        /// <param name="idx">Selected tab page index</param>
        /// <param name="iName">New name</param>
        public void RenameOMXParamPageProps(int idx, string iName)
        {
            atpc.OMXStructPageUpdateName(idx, iName);
        }

        /// <summary>
        /// Updates an OMX component instance id.
        /// </summary>
        /// <param name="idx">Selected tab page index</param>
        /// <param name="iId">Component instance id</param>
        public void UpdateOMXCompInstanceId(int idx, uint iId)
        {
            atpc.OMXStructPageUpdateCompInstanceId(idx, iId);
        }

        /// <summary>
        /// Selects a specified tab page containing OMX Param settings.
        /// </summary>
        /// <param name="idx">OMX Param page index</param>
        public void SelectOMXPage(int idx)
        {
            atpc.SelectedIndex = idx;
        }

        /// <summary>
        /// Clear the user defined controls from the AEUCTabbedParentControl object.
        /// </summary>
        public void ClearUserDefinedInterfaceTabs()
        {
            atpc.ClrTabPages();
        }

        /// <summary>
        /// Loads a user definied interface from a file.
        /// </summary>
        /// <param name="fInf">File info object containing the user definition</param>
        public void LoadUserSettingDefinitionsFile(FileInfo fInf)
        {
            atpc.FileLoad(fInf);
        }

        /// <summary>
        /// Loads a user definied interface from a file without showing progressbars
        /// </summary>
        /// <param name="fInf">File info object containing the user definition</param>
        public void LoadUserSettingDefinitionsFileNoProgBar(FileInfo fInf)
        {
            atpc.RunningNoGUI(true);
            pic.RunningNoGUI(true);
            atpc.FileLoad(fInf);
        }

        /// <summary>
        /// Save user defined settings to file
        /// </summary>
        /// <param name="fInf">FileInfo object to save the user definition to</param>
        public void SaveUserSettingDefinitionsFile(FileInfo fInf)
        {
            atpc.FileSave(fInf);
        }

        /// <summary>
        /// Returns the currently bound sys data transfer message  id
        /// </summary>
        /// <returns>Message id</returns>
        public uint GetBoundDataMessageID()
        {
            if (atpc.cmcDefinitios.msgSYSDataMsg != null)
                return atpc.cmcDefinitios.msgSYSDataMsg.msgId.UID;
            else
                return uint.MaxValue;
        }
        /// <summary>
        /// Returns the currently bound sys data transfer message control statuses
        /// </summary>
        /// <returns>Status id array</returns>
        public uint[] GetBoundDataMessageControlStat()
        {
            uint[] ctrlStatus = new uint[5];

            ctrlStatus[0] = ctrlStatus[1] = ctrlStatus[2] = ctrlStatus[3] = ctrlStatus[4] = uint.MaxValue;

            if (atpc.cmcDefinitios.msgCtrlStatDataInit != null)
            {
                ctrlStatus[0] = atpc.cmcDefinitios.msgCtrlStatDataInit.UID;
            }

            if (atpc.cmcDefinitios.msgCtrlStatDataFull != null)
            {
                ctrlStatus[1] = atpc.cmcDefinitios.msgCtrlStatDataFull.UID;
            }

            if (atpc.cmcDefinitios.msgCtrlStatDataStart != null)
            {
                ctrlStatus[2] = atpc.cmcDefinitios.msgCtrlStatDataStart.UID;
            }

            if (atpc.cmcDefinitios.msgCtrlStatDataMore != null)
            {
                ctrlStatus[3] = atpc.cmcDefinitios.msgCtrlStatDataMore.UID;
            }

            if (atpc.cmcDefinitios.msgCtrlStatDataEnd != null)
            {
                ctrlStatus[4] = atpc.cmcDefinitios.msgCtrlStatDataEnd.UID;
            }

            return ctrlStatus;
        }
        /// <summary>
        /// Returns the currently bound sys data transfer message data types
        /// </summary>
        /// <returns>Status id array</returns>
        public uint[] GetBoundDataMessageDataTypes()
        {
            uint[] dataTypes = new uint[2];

            dataTypes[0] = dataTypes[1] =  uint.MaxValue;

            if (atpc.cmcDefinitios.msgCtrlStatDataTypeJpeg != null)
            {
                dataTypes[0] = atpc.cmcDefinitios.msgCtrlStatDataTypeJpeg.UID;
            }

            if (atpc.cmcDefinitios.msgCtrlStatDataTypeInfo != null)
            {
                dataTypes[1] = atpc.cmcDefinitios.msgCtrlStatDataTypeInfo.UID;
            }

            return dataTypes;
        }
        #endregion

        #region AEUC sending/updating functionality
        #region Auxiliaries for bytestream composition/parsing

        /// <summary>
        /// Message header preparation function.
        /// </summary>
        /// <param name="gtpp">Tab page properties to get related message id and status, struct id, component id, port number</param>
        /// <param name="requestSettings">Flag indicating if settings are sent or request for setting is sent</param>
        /// <param name="msgPldSz">Payload size</param>
        /// <param name="msgHdr">Byte array reference</param>
        /// <returns>Position in the byte array after header preperation - header size value</returns>
        public int prepareMsgHeader(GenTabPageProperties gtpp, Boolean requestSettings, uint msgPldSz, out byte[] msgHdr)
        {
            int i = 0;
            uint MsgPldSize = msgPldSz + 12;
            msgHdr = new byte[24];
            
            uint msgId = gtpp.TabRelMSGId;
            if(requestSettings)
                msgId = gtpp.TabRelRqstMSGId;
            uint msgStat = gtpp.TabRelMSGStatus;
            uint compId = gtpp.TabRelCompId; 
            uint structID = gtpp.TabId;
            uint portNum = gtpp.TabIdExtra;

            //Message id
            msgHdr[i++] = (byte)(msgId >> 0);
            msgHdr[i++] = (byte)(msgId >> 8);
            msgHdr[i++] = (byte)(msgId >> 16);
            msgHdr[i++] = (byte)(msgId >> 24);

            //Message status
            msgHdr[i++] = (byte)(msgStat >> 0);
            msgHdr[i++] = (byte)(msgStat >> 8);
            msgHdr[i++] = (byte)(msgStat >> 16);
            msgHdr[i++] = (byte)(msgStat >> 24);

            //Message payload size
            msgHdr[i++] = (byte)(MsgPldSize >> 0);
            msgHdr[i++] = (byte)(MsgPldSize >> 8);
            msgHdr[i++] = (byte)(MsgPldSize >> 16);
            msgHdr[i++] = (byte)(MsgPldSize >> 24);

            //Component id
            msgHdr[i++] = (byte)(compId >> 0);
            msgHdr[i++] = (byte)(compId >> 8);
            msgHdr[i++] = (byte)(compId >> 16);
            msgHdr[i++] = (byte)(compId >> 24);

            //Struct id
            msgHdr[i++] = (byte)(structID >> 0);
            msgHdr[i++] = (byte)(structID >> 8);
            msgHdr[i++] = (byte)(structID >> 16);
            msgHdr[i++] = (byte)(structID >> 24);

            //Port number
            msgHdr[i++] = (byte)(portNum >> 0);
            msgHdr[i++] = (byte)(portNum >> 8);
            msgHdr[i++] = (byte)(portNum >> 16);
            msgHdr[i++] = (byte)(portNum >> 24);

            return i;
        }

        /// <summary>
        /// Returns an array of all the tab page property objects
        /// </summary>
        /// <returns>Array of tab page property objects</returns>
        public GenTabPageProperties[] getTabPageProps()
        {
            return atpc.gtpProperties.ToArray();
        }
        /// <summary>
        /// Return an array of all of the component related messaging
        /// </summary>
        /// <returns>Array of all of the component related messaging</returns>
        public GenMSG[] getCMsgDefs()
        {
            return atpc.cmcDefinitios.AEUC_MSG.ToArray();
        }
        #endregion

        #region Reading OMX parameter structure from a remote IL client
        /// <summary>
        /// Possible parameter stream parsing results and events
        /// </summary>
        public enum ParameterStreamParseResult
        {
            /// <summary>
            /// Success
            /// </summary>
            PARSE_OK,
            /// <summary>
            /// Wrong parameters or wrong command usage
            /// </summary>
            PARSE_FAIL,
            /// <summary>
            /// Unrecognized tokens while parsing
            /// </summary>
            PARSE_UNRECOGNIZED,
            /// <summary>
            /// Previously sent configuration has been applied correctly
            /// </summary>
            CONFIG_APPLY_ACK,
            /// <summary>
            /// OMX Component handle received
            /// </summary>
            OMX_COMP_HANDLE,
            /// <summary>
            /// Component ports information received
            /// </summary>
            OMX_COMP_PORTS_INFO,
            /// <summary>
            /// Component's port buffer allocation update
            /// </summary>
            OMX_COMP_PORT_BUFF_ALLOC,
            /// <summary>
            /// Components linkage update
            /// </summary>
            OMX_COMP_LINK,
            /// <summary>
            /// OMX component command message
            /// </summary>
            OMX_COMP_CMD,
            /// <summary>
            /// System marshalling - memory allocated
            /// </summary>
            SYS_MARSHAL_ALLOC,
            /// <summary>
            /// System marshalling - memory deallocated
            /// </summary>
            SYS_MARSHAL_FREE,
            /// <summary>
            /// System marshalling - memory copied
            /// </summary>
            SYS_MARSHAL_COPY,
            /// <summary>
            /// System marshalling - memory dumped
            /// </summary>
            SYS_MARSHAL_DUMP,
            /// <summary>
            /// DCC URI information received
            /// </summary>
            DCC_URI_INFO
        }
        /// <summary>
        /// Possible parameter stream parsing results and events
        /// </summary>
        public enum serviceEvents
        {
            /// <summary>
            /// Component instance id update event
            /// </summary>
            COMP_INST_UPDATE,
            /// <summary>
            /// Unrecognized tokens while parsing
            /// </summary>
            PARSE_UNRECOGNIZED
        }
        /// <summary>
        /// Structure containing array with all ports information of a component
        /// </summary>
        public struct CompPortInfo
        {
            /// <summary>
            /// Component id
            /// </summary>
            public int compId;
            /// <summary>
            /// Array containing information for all discovered ports
            /// </summary>
            public PortInfo[] ports;
        }
        /// <summary>
        /// Structure containing port information
        /// </summary>
        public struct PortInfo
        {
            /// <summary>
            /// Port number
            /// </summary>
            public int portNum;
            /// <summary>
            /// Port direction
            /// </summary>
            public int portDir;
            /// <summary>
            /// Port domain
            /// </summary>
            public int portDom;
        }

        public struct CompInstInfo
        {
            public string name;
            public int id;
        }
        /// <summary>
        /// Parameter stream parse delegate for event forwarding
        /// </summary>
        /// <param name="state">Parsing status</param>
        /// <param name="compId">Related component id</param>
        /// <param name="tabId">ID of the UI tab that got updated</param>
        public delegate void paramsStreamParse(ParameterStreamParseResult state, int compId, int tabId);

        /// <summary>
        /// Component generated event (acknowledge, status report/update, etc.)
        /// </summary>
        /// <param name="updateEvent">Event id</param>
        /// <param name="data">Event data</param>
        public delegate void omxCompUpdate(ParameterStreamParseResult updateEvent, object data);

        /// <summary>
        /// Parameter stream parse event.
        /// </summary>
        public event paramsStreamParse OnParamsStreamParse;

        /// <summary>
        /// Component instance id returned event.
        /// </summary>
        public event omxCompUpdate OnCompInstUpdate;

        void processReceivedPayloadStruct(GenMSG prcMsg)
        {
            //As thats not runing on the UI, invoke the UI thread to set the new values.
            if (InvokeRequired)
            {
                BeginInvoke(new ProcessReceivedPayloadDelegate(processReceivedPayloadStruct), new object[] { prcMsg });
            }
            else
            {
                bool tabPageFound = false;
                for (int i = 0; i < atpc.gtpProperties.Count; i++)
                {
                    if (prcMsg.msgId.UID == atpc.gtpProperties[i].TabRelRqstMSGId &&
                            (UInt32)prcMsg.payloadStruct[prcMsg.payloadStruct["structId"]] == atpc.gtpProperties[i].TabId &&
                            (UInt32)prcMsg.payloadStruct[prcMsg.payloadStruct["portNum"]] == atpc.gtpProperties[i].TabIdExtra)
                    {
                        #region Process OMX Settings update for specific structure
                        prcMsg.payloadStruct = new GenPayloadStruct("", atpc.gtpProperties[i].GetSettingArray, atpc.gtpProperties[i].TabRelCompId, atpc.gtpProperties[i].TabId, atpc.gtpProperties[i].TabIdExtra);
                        prcMsg.ParseMessageData();

                        paramsStructureSettingsParse(prcMsg.payloadStruct, atpc.gtpProperties[i].GetSettingArray);

                        if (OnParamsStreamParse != null)
                            OnParamsStreamParse(ParameterStreamParseResult.PARSE_OK,  (int)((UInt32)prcMsg.payloadStruct[prcMsg.payloadStruct["compId"]]), i);
                        if (OnCompInstUpdate != null)
                            OnCompInstUpdate(ParameterStreamParseResult.PARSE_OK, prcMsg);
                        #endregion
                        tabPageFound = true;
                    }
                    else if (prcMsg.msgId.UID == atpc.gtpProperties[i].TabRelMSGId &&
                                (UInt32)prcMsg.payloadStruct[prcMsg.payloadStruct["structId"]] == atpc.gtpProperties[i].TabId &&
                                (UInt32)prcMsg.payloadStruct[prcMsg.payloadStruct["portNum"]] == atpc.gtpProperties[i].TabIdExtra)
                    {
                        #region Process OMX Settings applied acknowledge
                        if (OnParamsStreamParse != null)
                            OnParamsStreamParse(ParameterStreamParseResult.CONFIG_APPLY_ACK,  (int)((UInt32)prcMsg.payloadStruct[prcMsg.payloadStruct["compId"]]), i);
                        if (OnCompInstUpdate != null)
                            OnCompInstUpdate(ParameterStreamParseResult.PARSE_OK, prcMsg);
                        #endregion
                        tabPageFound = true;
                    }
                }
                if (!tabPageFound)
                {
                    #region Process unrecognized bytestream
                    /*MessageBox.Show("Received \n\tmsg id: " + tst.msgId.UID.ToString() +
                                 "\n\tmsg status: " + tst.msgStatus.UID.ToString() +
                                 "\n\tmsg size: " + tst.msgPayloadSize.ToString() +
                                 "\nNo user defined representation found.");*/
                    if (OnParamsStreamParse != null)
                        OnParamsStreamParse(ParameterStreamParseResult.PARSE_UNRECOGNIZED, -1, 0);
                    #endregion
                }
            }
        }

        /// <summary>
        /// CommLink OnMessageReceived event handler.
        /// </summary>
        /// <param name="msgData">Message data byte array</param>
        void commLink_OnMessageReceived(byte[] msgData)
        {
            GenMSGId tstId = new GenMSGId();
            GenMSGStatus tstStatus = new GenMSGStatus();
            GenMSG tst = new GenMSG(atpc, tstId, tstStatus, null, false);
            tst.msgBytestream = msgData;

            tst.ParseMessageDataHeaderOnly();

            if (atpc.cmcDefinitios.msgSYSDataMsg != null && tst.msgId.UID == atpc.cmcDefinitios.msgSYSDataMsg.msgId.UID)
            {
                //Quit further parsing attempts - this message can't be handled at this level.
                return;
            }
            //If the message id is a component instantiate acknowledge, notify subscribers and stop further parsing.
            if (atpc.cmcDefinitios.msgOMXGetCompInstance != null && tst.msgId.UID == atpc.cmcDefinitios.msgOMXGetCompInstance.msgId.UID)
            {
                #region Process OMX Get component handle acknoweldge
                tst.payloadStruct = new GenPayloadStruct("", null);
                #region Add component id payload item
                char[] compName = new char[tst.msgPayloadSize - 5];
                for (int i = 0; i < compName.Length - 1; i++)
                    compName[i] = 'x';
                IAEUCSetting[] runTVar = new IAEUCSetting[2];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "Component id";
                runTVar[0].AEUC_Id = 0;
                runTVar[1] = new GenPayloadStruct.NewPldItem();
                runTVar[1].AEUC_DisplayName = "Component Name";
                runTVar[1].AEUC_Id = 1;
                #endregion
                tst.payloadStruct.SetPayloadItems(runTVar);
                tst.payloadStruct.setStringItem(1, new string(compName));
                tst.ParseMessageData();

                CompInstInfo compId = new CompInstInfo();
                compId.id = (int)((UInt32)tst.payloadStruct[0]);//Access first item in bytestream that should be the component instance id.
                compId.name = tst.payloadStruct.getParamStringVal(1);
                if (OnCompInstUpdate != null)//If there are subscribers, notify them of the returned component instance id.
                    OnCompInstUpdate(ParameterStreamParseResult.OMX_COMP_HANDLE, compId);
                if (OnParamsStreamParse != null)
                    OnParamsStreamParse(ParameterStreamParseResult.OMX_COMP_HANDLE, compId.id, 0);
                #endregion
                //Quit further parsing attempts - this message can't be treated further as no valid payload data should be present.
                return;
            }
            //If the message id is a get component ports acknowledge, notify subscribers and stop further parsing.
            if (atpc.cmcDefinitios.msgOMXGetCompPorts != null && tst.msgId.UID == atpc.cmcDefinitios.msgOMXGetCompPorts.msgId.UID)
            {
                #region Process OMX Get component ports acknoweldge
                tst.payloadStruct = new GenPayloadStruct("", null);
                #region Add component id payload item
                //Number of items in the array is payload size minus the component id divided by the items size
                int arraySz = (int)(tst.msgPayloadSize - 4) / (3 * 4);
                IAEUCSetting[] runTVar = new IAEUCSetting[1 + arraySz * 3];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "Component id";
                runTVar[0].AEUC_Id = 0;
                for (int i = 0; i < arraySz; i++)
                {
                    int ittr = i * 3 + 1;

                    runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                    runTVar[ittr].AEUC_DisplayName = "Port number";
                    runTVar[ittr].AEUC_Id = (uint)ittr;

                    ittr += 1;

                    runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                    runTVar[ittr].AEUC_DisplayName = "Port direction";
                    runTVar[ittr].AEUC_Id = (uint)ittr;

                    ittr += 1;

                    runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                    runTVar[ittr].AEUC_DisplayName = "Port domain";
                    runTVar[ittr].AEUC_Id = (uint)ittr;
                }
                #endregion
                tst.payloadStruct.SetPayloadItems(runTVar);
                tst.ParseMessageData();

                int compId =  (int)((UInt32)tst.payloadStruct[0]);//Access first item in bytestream that should be the component instance id.
                CompPortInfo portInfo = new CompPortInfo();
                portInfo.compId = compId;
                portInfo.ports = new PortInfo[arraySz];
                for (int i = 0; i < arraySz; i++)
                {
                    #region Get ports information
                    int ittr = i * 3 + 1;
                    portInfo.ports[i].portNum =  (int)((UInt32)tst.payloadStruct[(ulong)ittr]);
                    ittr += 1;
                    portInfo.ports[i].portDir =  (int)((UInt32)tst.payloadStruct[(ulong)ittr]);
                    ittr += 1;
                    portInfo.ports[i].portDom =  (int)((UInt32)tst.payloadStruct[(ulong)ittr]);
                    #endregion
                }
                if (OnCompInstUpdate != null)//If there are subscribers, notify them of the returned component instance id.
                    OnCompInstUpdate(ParameterStreamParseResult.OMX_COMP_PORTS_INFO, portInfo);
                if (OnParamsStreamParse != null)
                    OnParamsStreamParse(ParameterStreamParseResult.OMX_COMP_PORTS_INFO, compId, 0);
                #endregion
                //Quit further parsing attempts - this message can't be treated further as no valid payload data should be present.
                return;
            }
            //If the message id is a component port buffers alloc acknowledge, notify subscribers and stop further parsing.
            if (atpc.cmcDefinitios.msgOMXAllocPortBuffs != null && tst.msgId.UID == atpc.cmcDefinitios.msgOMXAllocPortBuffs.msgId.UID)
            {
                #region Process OMX component port buffers alloc acknoweldge
                tst.payloadStruct = new GenPayloadStruct("", null);
                #region Add component id payload item
                IAEUCSetting[] runTVar = new IAEUCSetting[1];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "Component id";
                runTVar[0].AEUC_Id = 0;
                #endregion
                tst.payloadStruct.SetPayloadItems(runTVar);
                tst.ParseMessageData();

                int compId =  (int)((UInt32)tst.payloadStruct[0]);//Access first item in bytestream that should be the component instance id.
                if (OnCompInstUpdate != null)//If there are subscribers, notify them of the returned component instance id.
                    OnCompInstUpdate(ParameterStreamParseResult.OMX_COMP_PORT_BUFF_ALLOC, compId);
                if (OnParamsStreamParse != null)
                    OnParamsStreamParse(ParameterStreamParseResult.OMX_COMP_PORT_BUFF_ALLOC, compId, 0);
                #endregion
                //Quit further parsing attempts - this message can't be treated further as no valid payload data should be present.
                return;
            }
            //If the message id is a component linkage acknowledge, notify subscribers and stop further parsing.
            if (atpc.cmcDefinitios.msgOMXLinkCompPorts != null && tst.msgId.UID == atpc.cmcDefinitios.msgOMXLinkCompPorts.msgId.UID)
            {
                #region Process OMX component link acknoweldge
                tst.payloadStruct = new GenPayloadStruct("", null);
                #region Add component id payload item
                IAEUCSetting[] runTVar = new IAEUCSetting[1];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "Component id";
                runTVar[0].AEUC_Id = 0;
                #endregion
                tst.payloadStruct.SetPayloadItems(runTVar);
                tst.ParseMessageData();

                int compId =  (int)((UInt32)tst.payloadStruct[0]);//Access first item in bytestream that should be the component instance id.
                if (OnCompInstUpdate != null)//If there are subscribers, notify them of the returned component instance id.
                    OnCompInstUpdate(ParameterStreamParseResult.OMX_COMP_LINK, compId);
                if (OnParamsStreamParse != null)
                    OnParamsStreamParse(ParameterStreamParseResult.OMX_COMP_LINK, compId, 0);
                #endregion
                //Quit further parsing attempts - this message can't be treated further as no valid payload data should be present.
                return;
            }
            //If the message id is a get component ports acknowledge, notify subscribers and stop further parsing.
            if (atpc.cmcDefinitios.msgOMXCompCmds != null && tst.msgId.UID == atpc.cmcDefinitios.msgOMXCompCmds.msgId.UID)
            {
                #region Process OMX Get component ports acknoweldge
                tst.payloadStruct = new GenPayloadStruct("", null);
                #region Add component id payload item
                IAEUCSetting[] runTVar = new IAEUCSetting[4];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "Component id";
                runTVar[0].AEUC_Id = 0;

                runTVar[1] = new GenPayloadStruct.NewPldItem();
                runTVar[1].AEUC_DisplayName = "Command";
                runTVar[1].AEUC_Id = (uint)1;

                runTVar[2] = new GenPayloadStruct.NewPldItem();
                runTVar[2].AEUC_DisplayName = "Param";
                runTVar[2].AEUC_Id = (uint)2;

                runTVar[3] = new GenPayloadStruct.NewPldItem();
                runTVar[3].AEUC_DisplayName = "Command data";
                runTVar[3].AEUC_Id = (uint)3;
                #endregion
                tst.payloadStruct.SetPayloadItems(runTVar);
                tst.ParseMessageData();

                int compId = (int)((UInt32)tst.payloadStruct[0]);//Access first item in bytestream that should be the component instance id.
                if (OnCompInstUpdate != null)//If there are subscribers, notify them of the returned component instance id.
                    OnCompInstUpdate(ParameterStreamParseResult.OMX_COMP_CMD, compId);
                if (OnParamsStreamParse != null)
                    OnParamsStreamParse(ParameterStreamParseResult.OMX_COMP_CMD, compId, 0);
                #endregion
                //Quit further parsing attempts - this message can't be treated further as no valid payload data should be present.
                return;
            }
            if (atpc.cmcDefinitios.msgSYSMarshalAlloc != null && tst.msgId.UID == atpc.cmcDefinitios.msgSYSMarshalAlloc.msgId.UID)
            {
                #region Process System marshalling memory allocation acknoweldge
                tst.payloadStruct = new GenPayloadStruct("", null);
                #region Add component id payload item
                IAEUCSetting[] runTVar = new IAEUCSetting[3];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "ComponentId";
                runTVar[0].AEUC_Id = 0;

                runTVar[1] = new GenPayloadStruct.NewPldItem();
                runTVar[1].AEUC_DisplayName = "Size";
                runTVar[1].AEUC_Id = (uint)1;

                runTVar[2] = new GenPayloadStruct.NewPldItem();
                runTVar[2].AEUC_DisplayName = "Pointer";
                runTVar[2].AEUC_Id = (uint)2;
                #endregion
                tst.payloadStruct.SetPayloadItems(runTVar);
                tst.ParseMessageData();

                int compId =  (int)((UInt32)tst.payloadStruct[0]);//Access first item in bytestream that should be the component instance id.
                if (OnCompInstUpdate != null)//If there are subscribers, notify them of the returned component instance id.
                    OnCompInstUpdate(ParameterStreamParseResult.SYS_MARSHAL_ALLOC, tst);
                if (OnParamsStreamParse != null)
                    OnParamsStreamParse(ParameterStreamParseResult.SYS_MARSHAL_ALLOC, compId, 0);
                #endregion
                //Quit further parsing attempts - this message can't be handled at this level.
                return;
            }
            if (atpc.cmcDefinitios.msgSYSMarshalFree != null && tst.msgId.UID == atpc.cmcDefinitios.msgSYSMarshalFree.msgId.UID)
            {
                #region Process System marshalling memory deallocation acknoweldge
                tst.payloadStruct = new GenPayloadStruct("", null);
                #region Add component id payload item
                IAEUCSetting[] runTVar = new IAEUCSetting[3];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "ComponentId";
                runTVar[0].AEUC_Id = 0;

                runTVar[1] = new GenPayloadStruct.NewPldItem();
                runTVar[1].AEUC_DisplayName = "Size";
                runTVar[1].AEUC_Id = (uint)1;

                runTVar[2] = new GenPayloadStruct.NewPldItem();
                runTVar[2].AEUC_DisplayName = "Pointer";
                runTVar[2].AEUC_Id = (uint)2;
                #endregion
                tst.payloadStruct.SetPayloadItems(runTVar);
                tst.ParseMessageData();

                int compId =  (int)((UInt32)tst.payloadStruct[0]);//Access first item in bytestream that should be the component instance id.
                if (OnCompInstUpdate != null)//If there are subscribers, notify them of the returned component instance id.
                    OnCompInstUpdate(ParameterStreamParseResult.SYS_MARSHAL_FREE, tst);
                if (OnParamsStreamParse != null)
                    OnParamsStreamParse(ParameterStreamParseResult.SYS_MARSHAL_FREE, compId, 0);
                #endregion
                //Quit further parsing attempts - this message can't be handled at this level.
                return;
            }
            if (atpc.cmcDefinitios.msgSYSMarshalCopy != null && tst.msgId.UID == atpc.cmcDefinitios.msgSYSMarshalCopy.msgId.UID)
            {
                #region Process System marshalling memory copy acknoweldge
                tst.payloadStruct = new GenPayloadStruct("", null);
                #region Add component id payload item
                IAEUCSetting[] runTVar = new IAEUCSetting[3];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "ComponentId";
                runTVar[0].AEUC_Id = 0;

                runTVar[1] = new GenPayloadStruct.NewPldItem();
                runTVar[1].AEUC_DisplayName = "Size";
                runTVar[1].AEUC_Id = (uint)1;

                runTVar[2] = new GenPayloadStruct.NewPldItem();
                runTVar[2].AEUC_DisplayName = "Pointer";
                runTVar[2].AEUC_Id = (uint)2;
                #endregion
                tst.payloadStruct.SetPayloadItems(runTVar);
                tst.ParseMessageData();

                int compId =  (int)((UInt32)tst.payloadStruct[0]);//Access first item in bytestream that should be the component instance id.
                if (OnCompInstUpdate != null)//If there are subscribers, notify them of the returned component instance id.
                    OnCompInstUpdate(ParameterStreamParseResult.SYS_MARSHAL_COPY, tst);
                if (OnParamsStreamParse != null)
                    OnParamsStreamParse(ParameterStreamParseResult.SYS_MARSHAL_COPY, compId, 0);
                #endregion
                //Quit further parsing attempts - this message can't be handled at this level.
                return;
            }
            if (atpc.cmcDefinitios.msgSYSMarshalDump != null && tst.msgId.UID == atpc.cmcDefinitios.msgSYSMarshalDump.msgId.UID)
            {
                #region Process System marshalling memory copy acknoweldge
                tst.payloadStruct = new GenPayloadStruct("", null);
                #region Add component id payload item
                IAEUCSetting[] runTVar = new IAEUCSetting[3];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "ComponentId";
                runTVar[0].AEUC_Id = 0;

                runTVar[1] = new GenPayloadStruct.NewPldItem();
                runTVar[1].AEUC_DisplayName = "Size";
                runTVar[1].AEUC_Id = (uint)1;

                runTVar[2] = new GenPayloadStruct.NewPldItem();
                runTVar[2].AEUC_DisplayName = "Pointer";
                runTVar[2].AEUC_Id = (uint)2;
                #endregion
                tst.payloadStruct.SetPayloadItems(runTVar);
                tst.ParseMessageData();

                int compId =  (int)((UInt32)tst.payloadStruct[0]);//Access first item in bytestream that should be the component instance id.
                if (OnCompInstUpdate != null)//If there are subscribers, notify them of the returned component instance id.
                    OnCompInstUpdate(ParameterStreamParseResult.SYS_MARSHAL_DUMP, tst);
                if (OnParamsStreamParse != null)
                    OnParamsStreamParse(ParameterStreamParseResult.SYS_MARSHAL_DUMP, compId, 0);
                #endregion
                //Quit further parsing attempts - this message can't be handled at this level.
                return;
            }

            if (atpc.cmcDefinitios.msgOMXGetCompConf != null && tst.msgId.UID == atpc.cmcDefinitios.msgOMXGetCompConf.msgId.UID ||
                atpc.cmcDefinitios.msgOMXSetCompConf != null && tst.msgId.UID == atpc.cmcDefinitios.msgOMXSetCompConf.msgId.UID ||
                atpc.cmcDefinitios.msgOMXGetCompParam != null && tst.msgId.UID == atpc.cmcDefinitios.msgOMXGetCompParam.msgId.UID ||
                atpc.cmcDefinitios.msgOMXSetCompParam != null && tst.msgId.UID == atpc.cmcDefinitios.msgOMXSetCompParam.msgId.UID)
            {
                tst.ParseMessageData();
                //If there is any payload attempt to process the data.
                if (tst.payloadStruct != null)
                {
                    #region Save message header data
                    //Get the message header size and save the message header data for laterz...
                    uint hdrSz = (uint)tst.GetMsgHeaderBytestreamSize();
                    byte[] hdrData = new byte[hdrSz];
                    for (int i = 0; i < hdrSz; i++)
                        hdrData[i] = tst.msgBytestream[i];
                    #endregion

                    //Do while there is byte data in the payload - in case of multiple structure payload
                    while (tst.msgPayloadSize > 0)
                    {
                        #region Parse and process message data
                        //Parse the OMX struct header data
                        tst.ParseMessageData();
                        //Try to process the struct-bytrestream
                        processReceivedPayloadStruct(tst);
                        #endregion
                        #region Update payload size - subtract processed struct size
                        //Subtract the size of the processed struct from the payload - in case there are several structs
                        //stuffed in the same message payload
                        ulong structSize = (ulong)((UInt32)tst.payloadStruct[tst.payloadStruct["structSizeSystemParameter"]]);
                        tst.msgPayloadSize -= structSize;
                        #endregion
                        #region If there are more structs create new payload array without the just processed one
                        //If there are bytes remaining in the playload that should mean that there are more struct data in the
                        //same message payload .
                        if ((int)tst.msgPayloadSize < 0)
                            tst.msgPayloadSize = 0;
                        if (tst.msgPayloadSize > 0)
                        {
                            //Copy the remaining of the payload into a new byte array (omitting the already processed struct)
                            byte[] tmpPldData = new byte[tst.msgPayloadSize];
                            for (ulong i = 0; i < tst.msgPayloadSize; i++)
                                tmpPldData[i] = tst.msgBytestream[hdrSz + structSize + i];

                            //Create a new payload compozed of the message header and the remaining unprocessed payload bytes
                            tst.msgBytestream = new byte[hdrSz + tst.msgPayloadSize];
                            hdrData.CopyTo(tst.msgBytestream, 0);
                            tmpPldData.CopyTo(tst.msgBytestream, hdrSz);
                        }
                        #endregion
                    }
                }
                else
                {
                    #region Process unrecognized bytestream
                    commLink.errorMessage("Received \n\tmsg id: " + tst.msgId.UID.ToString() +
                                            "\n\tmsg status: " + tst.msgStatus.UID.ToString() +
                                            "\n\tmsg size: " + tst.msgPayloadSize.ToString() +
                                            "\nNo user defined representation found.");
                    if (OnParamsStreamParse != null)
                        OnParamsStreamParse(ParameterStreamParseResult.PARSE_UNRECOGNIZED, -1, 0);
                    #endregion
                }
            }
        }

        /// <summary>
        /// Sends a settings request message
        /// </summary>
        void send_omx_sett_read_request_msg()
        {
            GenMSGId tstId = new GenMSGId();
            tstId.UID = atpc.gtpProperties[atpc.SelectedIndex].TabRelRqstMSGId;

            GenMSGStatus tstStatus = new GenMSGStatus();
            tstStatus.UID = atpc.gtpProperties[atpc.SelectedIndex].TabRelMSGStatus;

            GenMSG tst = new GenMSG(atpc, tstId, tstStatus, null, atpc.TabPages[atpc.SelectedIndex], false);

            commLink.msgSendData(tst.GenerateMessage(null));
        }

        delegate void ProcessReceivedPayloadDelegate(GenMSG prcMsg);

        delegate void ParamParseDelegate(GenPayloadStruct generated_values, IAEUCSetting[] total_settings);

        /// <summary>
        /// Parses and displays the read settings stream
        /// </summary>
        /// <param name="aeucSettData">Payload object</param>
        /// <param name="aeucUIElements">array of the payload associated IAEUCSetting elements</param>
        public void paramsStructureSettingsParse(GenPayloadStruct aeucSettData, IAEUCSetting[] aeucUIElements)
        {
            //As thats not runing on the UI, invoke the UI thread to set the new values.
            if (InvokeRequired)
            {
                BeginInvoke(new ParamParseDelegate(paramsStructureSettingsParse), new object[] { aeucSettData, aeucUIElements });
            }
            else
            {
                #region Set the parsed settings to the tab page controls
                for (int i = 0; i < aeucUIElements.Length; i++)
                {
                    try
                    {
                        switch(aeucUIElements[i].AEUC_Size)
                        {
                            case 1:
                                aeucUIElements[i].AEUC_Val = (long)((Byte)aeucSettData[aeucSettData[aeucUIElements[i].AEUC_DisplayName]]);
                                break;
                            case 2:
                                aeucUIElements[i].AEUC_Val = (long)((UInt16)aeucSettData[aeucSettData[aeucUIElements[i].AEUC_DisplayName]]);
                                break;
                            case 4:
                                aeucUIElements[i].AEUC_Val = (long)((UInt32)aeucSettData[aeucSettData[aeucUIElements[i].AEUC_DisplayName]]);
                                break;
                            default:
                                UInt64 tmpVal = 0;
                                Byte[] tmpAr = (Byte[])aeucSettData[aeucSettData[aeucUIElements[i].AEUC_DisplayName]];
                                if (tmpAr.Length != aeucUIElements[i].AEUC_Size)
                                    throw new Exception("Bytestream missmathc!");

                                for (int ik = 0; ik < tmpAr.Length; ik++)
                                {
                                    tmpVal |= ((UInt64)tmpAr[ik]) << (8 * ik);
                                }

                                aeucUIElements[i].AEUC_Val = (long)tmpVal;
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        commLink.errorMessage(ex.Message);
                    }
                }
                #endregion
            }
        }
        #endregion

        #region Sending OMX parameter structure to remote IL client
        /// <summary>
        /// Acquire all of the AEUC setting values and pack them into a bytestream representation of the desired structure (defined by tab page props.)
        /// </summary>
        void paramsStructureSettingsTransfer()
        {
            GenMSGId tstId = new GenMSGId();
            tstId.UID = atpc.gtpProperties[atpc.SelectedIndex].TabRelMSGId;
            
            GenMSGStatus tstStatus = new GenMSGStatus();
            tstStatus.UID = atpc.gtpProperties[atpc.SelectedIndex].TabRelMSGStatus;
            
            GenMSG tst = new GenMSG(atpc, tstId, tstStatus, null, atpc.TabPages[atpc.SelectedIndex], false);

            bytestreamTransfer(tst.GenerateMessage(null));
        }
        /// <summary>
        /// Sends multiple configuration structures grouped by relevant send_data message id and message status
        /// </summary>
        /// <param name="selectedIndeces">Array of atpc tab page undeces to send</param>
        public void multiParamStructureSettingsTransfer(int[] selectedIndeces)
        {
            List<GenMSG> possMsgs = new List<GenMSG>();
            #region Discover all of the unique message ids present
            for (int i = 0; i < selectedIndeces.Length; i++)
            {
                bool present = false;
                for (int k = 0; k < possMsgs.Count && !present; k++)
                    if (possMsgs[k].msgId.UID == atpc.gtpProperties[selectedIndeces[i]].TabRelMSGId && possMsgs[k].msgStatus.UID == atpc.gtpProperties[selectedIndeces[i]].TabRelMSGStatus)
                        present = true;

                if (!present)
                {
                    GenMSGId tstId = new GenMSGId();
                    tstId.UID = atpc.gtpProperties[selectedIndeces[i]].TabRelMSGId;

                    GenMSGStatus tstStatus = new GenMSGStatus();
                    tstStatus.UID = atpc.gtpProperties[selectedIndeces[i]].TabRelMSGStatus;

                    possMsgs.Add(new GenMSG(atpc, tstId, tstStatus, null, false));
                }
            }
            #endregion
            //For all of the discovered unique message ids compose a bytestream containing all of the OMX structures
            for (int k = 0; k < possMsgs.Count; k++)
            {
                List<GenPayloadStruct> payloadStructs = new List<GenPayloadStruct>();
                #region Add the payloads of all of the OMX structures bearing the same message id/stat
                for (int i = 0; i < selectedIndeces.Length; i++)
                {
                    if (possMsgs[k].msgId.UID == atpc.gtpProperties[selectedIndeces[i]].TabRelMSGId && possMsgs[k].msgStatus.UID == atpc.gtpProperties[selectedIndeces[i]].TabRelMSGStatus)
                    {
                        payloadStructs.Add(new GenPayloadStruct("", atpc.gtpProperties[selectedIndeces[i]].GetSettingArray, atpc.gtpProperties[selectedIndeces[i]].TabRelCompId, atpc.gtpProperties[selectedIndeces[i]].TabId, atpc.gtpProperties[selectedIndeces[i]].TabIdExtra));
                    }
                }
                #endregion
                byte[] msgByteStream = null;
                #region Create the all-in-one bytestream containing all the OMX structure payloads
                for (int i = 0; i < payloadStructs.Count; i++)
                {
                    byte[] nwStream = payloadStructs[i].prepareByteStream();
                    if (msgByteStream == null)
                        msgByteStream = nwStream;
                    else
                    {
                        byte[] tpStream = new byte[msgByteStream.Length + nwStream.Length];
                        msgByteStream.CopyTo(tpStream, 0);
                        nwStream.CopyTo(tpStream, msgByteStream.Length);
                        msgByteStream = tpStream;
                    }
                }
                #endregion
                //Send the thus formed bytestream message
                bytestreamTransfer(possMsgs[k].GenerateMessage(msgByteStream));
            }
        }

        #region Memory marshalling

        #region Marshalling data
        List<GenPayloadStruct> mrshPayloadStructs;
        List<GenPayloadStruct.srzOfstMap> mrshSrzMap;

        uint MemF_componentId;
        FileInfo MemF_fInf;
        uint MemF_memPtr;
        uint MemF_memSz;
        List<string> sensors;
        bool uriEOF;
        AutoResetEvent MemF_areDoneCopy = new AutoResetEvent(false);

        ProgressBars.ProgBarsDisp progDisplay;

        public delegate void OperationComplete();
        public event OperationComplete OnOperationComplete;
        #endregion
        #region DCC data
        string dccURIinfo;
        uint dccURIinfoId;
        public delegate void DCCURIConllected(string[] sensors);
        public event DCCURIConllected OnDCCURICollected;

        OperationComplete opHandler = null;
        GenPayloadStruct DCCURIInfoStruct;
        #endregion

        /// <summary>
        /// Sends multiple configuration structures grouped by relevant send_data message id and message status
        /// </summary>
        /// <param name="selectedIndeces">Array of atpc tab page undeces to send</param>
        public void multiParamStructureSerialization(int[] selectedIndeces)
        {
            uint componentId = atpc.gtpProperties[selectedIndeces[0]].TabRelCompId;
            mrshPayloadStructs = new List<GenPayloadStruct>();
            mrshSrzMap = new List<GenPayloadStruct.srzOfstMap>();
            #region Add the payloads of all of the OMX structures bearing the same message id/stat
            for (int i = 0; i < selectedIndeces.Length; i++)
            {
                mrshPayloadStructs.Add(new GenPayloadStruct("", atpc.gtpProperties[selectedIndeces[i]].GetSettingArray));
                GenPayloadStruct.srzOfstMap tmpItm = new GenPayloadStruct.srzOfstMap();
                tmpItm.id = atpc.gtpProperties[selectedIndeces[i]].TabId;
                tmpItm.ofst = 0;
                mrshSrzMap.Add(tmpItm);
            }
            #endregion
            
            #region Create the serialization structure-address mapping
            uint strmUsg = 0;
            for (int i = 0; i < mrshPayloadStructs.Count; i++)
            {
                mrshSrzMap[i].ofst = strmUsg;
                strmUsg += (uint)mrshPayloadStructs[i].prepareByteStream().Length;
            }
            #endregion

            if (atpc.cmcDefinitios.msgSYSMarshalAlloc != null)
            {
                #region Prepare marhsalling memory allocation message
                OnCompInstUpdate += new omxCompUpdate(marshallAllocationDoneCopyStructs);

                GenPayloadStruct.NewPldItem[] runTVar = new GenPayloadStruct.NewPldItem[4];
                int ittr = 0;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "ComponentId";
                runTVar[ittr].AEUC_Val = componentId;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Size";
                runTVar[ittr].AEUC_Val = strmUsg;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Pointer";
                runTVar[ittr].AEUC_Val = 0;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Offset";
                runTVar[ittr].AEUC_Val = 0;
                runTVar[ittr].AEUC_Id = (uint)ittr++;
                #endregion

                GenPayloadStruct marshallAlloc = new GenPayloadStruct("marshall alloc", runTVar);
                bytestreamTransfer(atpc.cmcDefinitios.msgSYSMarshalAlloc.GenerateMessage(marshallAlloc.prepareByteStream()));
            }
            else
            {
                MessageBox.Show("System marshalling memory allocation message not bound!");
            }
        }

        void marshallAllocationDoneCopyStructs(UCTabPage.ParameterStreamParseResult updateEvent, object data)
        {
            if (updateEvent == ParameterStreamParseResult.SYS_MARSHAL_ALLOC)
            {
                if (atpc.cmcDefinitios.msgSYSMarshalCopy != null)
                {
                    GenMSG tst = (GenMSG)data;

                    OnCompInstUpdate -= new omxCompUpdate(marshallAllocationDoneCopyStructs);

                    int compId = (int)((UInt32)tst.payloadStruct[0]);//Access first item in bytestream that should be the component instance id.
                    uint mhsSize = (uint)((UInt32)tst.payloadStruct[1]);//Access second item in bytestream that should be the allocation size.
                    uint mhsPtr = (uint)((UInt32)tst.payloadStruct[2]);//Access third item in bytestream that should be the allocated pointer.

                    #region Apply the base pointer to all offsets
                    for (int i = 0; i < mrshSrzMap.Count; i++)
                    {
                        mrshSrzMap[i].ofst += mhsPtr;
                    }
                    #endregion
                    byte[] msgByteStream = null;
                    #region Prepare marhsalling memory copy message

                    GenPayloadStruct.NewPldItem[] runTVar = new GenPayloadStruct.NewPldItem[4];
                    int ittr = 0;

                    runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                    runTVar[ittr].AEUC_DisplayName = "ComponentId";
                    runTVar[ittr].AEUC_Val = compId;
                    runTVar[ittr].AEUC_Id = (uint)ittr++;

                    runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                    runTVar[ittr].AEUC_DisplayName = "Size";
                    runTVar[ittr].AEUC_Val = mhsSize;
                    runTVar[ittr].AEUC_Id = (uint)ittr++;

                    runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                    runTVar[ittr].AEUC_DisplayName = "Pointer";
                    runTVar[ittr].AEUC_Val = mhsPtr;
                    runTVar[ittr].AEUC_Id = (uint)ittr++;

                    runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                    runTVar[ittr].AEUC_DisplayName = "Offset";
                    runTVar[ittr].AEUC_Val = 0;
                    runTVar[ittr].AEUC_Id = (uint)ittr++;
                    #endregion
                    GenPayloadStruct marshallCopy = new GenPayloadStruct("marshall copy", runTVar);
                    #region Create the all-in-one bytestream containing all the OMX structure payloads
                    msgByteStream = marshallCopy.prepareByteStream();
                    for (int i = 0; i < mrshPayloadStructs.Count; i++)
                    {
                        byte[] nwStream = mrshPayloadStructs[i].prepareByteStream(mrshSrzMap.ToArray());
                        if (msgByteStream == null)
                            msgByteStream = nwStream;
                        else
                        {
                            byte[] tpStream = new byte[msgByteStream.Length + nwStream.Length];
                            msgByteStream.CopyTo(tpStream, 0);
                            nwStream.CopyTo(tpStream, msgByteStream.Length);
                            msgByteStream = tpStream;
                        }
                    }
                    #endregion

                    //Send the thus formed bytestream message
                    atpc.cmcDefinitios.msgSYSMarshalCopy.payloadStruct = null;
                    bytestreamTransfer(atpc.cmcDefinitios.msgSYSMarshalCopy.GenerateMessage(msgByteStream));
                }
                else
                {
                    MessageBox.Show("System marshalling memory copy message not bound!");
                }
            }
        }

        /// <summary>
        /// Sends memory allocation message
        /// </summary>
        /// <param name="componentId">Component id in which context to allocate the memory</param>
        /// <param name="memSize">Memory size in bytes to allocate</param>
        public void marshallingMemAlloc(uint componentId, int memSize)
        {
            if (atpc.cmcDefinitios.msgSYSMarshalAlloc != null)
            {
                #region Prepare marhsalling memory allocation message

                GenPayloadStruct.NewPldItem[] runTVar = new GenPayloadStruct.NewPldItem[4];
                int ittr = 0;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "ComponentId";
                runTVar[ittr].AEUC_Val = componentId;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Size";
                runTVar[ittr].AEUC_Val = memSize;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Pointer";
                runTVar[ittr].AEUC_Val = 0;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Offset";
                runTVar[ittr].AEUC_Val = 0;
                runTVar[ittr].AEUC_Id = (uint)ittr++;
                #endregion

                GenPayloadStruct marshallAlloc = new GenPayloadStruct("marshall alloc", runTVar);
                atpc.cmcDefinitios.msgSYSMarshalAlloc.payloadStruct = null;
                bytestreamTransfer(atpc.cmcDefinitios.msgSYSMarshalAlloc.GenerateMessage(marshallAlloc.prepareByteStream()));
            }
            else
            {
                MessageBox.Show("System marshalling memory allocation message not bound!");
            }
        }

        /// <summary>
        /// Sends memory allocation message and loads a file to that memory
        /// </summary>
        /// <param name="componentId">Component id in which context to allocate the memory</param>
        /// <param name="fInf">File to load</param>
        public void marshallingMemAllocFileLoad(uint componentId, FileInfo fInf)
        {
            if (atpc.cmcDefinitios.msgSYSMarshalAlloc != null)
            {
                MemF_fInf = fInf;

                if (fInf.Exists)
                {
                    #region Prepare marhsalling memory allocation message
                    OnCompInstUpdate += new omxCompUpdate(marshallAllocationDoneCopyFile);

                    GenPayloadStruct.NewPldItem[] runTVar = new GenPayloadStruct.NewPldItem[4];
                    int ittr = 0;

                    runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                    runTVar[ittr].AEUC_DisplayName = "ComponentId";
                    runTVar[ittr].AEUC_Val = componentId;
                    runTVar[ittr].AEUC_Id = (uint)ittr++;

                    runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                    runTVar[ittr].AEUC_DisplayName = "Size";
                    runTVar[ittr].AEUC_Val = fInf.Length;
                    runTVar[ittr].AEUC_Id = (uint)ittr++;

                    runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                    runTVar[ittr].AEUC_DisplayName = "Pointer";
                    runTVar[ittr].AEUC_Val = 0;
                    runTVar[ittr].AEUC_Id = (uint)ittr++;

                    runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                    runTVar[ittr].AEUC_DisplayName = "Offset";
                    runTVar[ittr].AEUC_Val = 0;
                    runTVar[ittr].AEUC_Id = (uint)ittr++;
                    #endregion

                    GenPayloadStruct marshallAlloc = new GenPayloadStruct("marshall alloc", runTVar);
                    atpc.cmcDefinitios.msgSYSMarshalAlloc.payloadStruct = null;
                    bytestreamTransfer(atpc.cmcDefinitios.msgSYSMarshalAlloc.GenerateMessage(marshallAlloc.prepareByteStream()));
                }
                else
                {
                    MessageBox.Show("Invalid file!");
                }
            }
            else
            {
                MessageBox.Show("System marshalling memory allocation message not bound!");
            }
        }

        void fileCopyingThread()
        {
            OnCompInstUpdate += new omxCompUpdate(marshallDoneCopyFile);
            BinaryReader bRd = new BinaryReader(MemF_fInf.OpenRead());

            ProgressBars.ProgBarsHdl tmpProgBar = progDisplay.CreateProgressBar(MemF_fInf.FullName);

            tmpProgBar.SetMaximum((int)bRd.BaseStream.Length);
            tmpProgBar.SetMinimum(0);
            if (bRd.BaseStream.Length > 1024)
                tmpProgBar.SetStep(1024);
            else
                tmpProgBar.SetStep((int)bRd.BaseStream.Length);

            for (int crntStrmPos = 0; crntStrmPos < bRd.BaseStream.Length; )
            {
                #region Prepare marhsalling memory copy message

                GenPayloadStruct.NewPldItem[] runTVar = new GenPayloadStruct.NewPldItem[4];
                int ittr = 0;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "ComponentId";
                runTVar[ittr].AEUC_Val = MemF_componentId;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Size";
                if (bRd.BaseStream.Length - crntStrmPos > 1024)
                    runTVar[ittr].AEUC_Val = 1024;
                else
                    runTVar[ittr].AEUC_Val = (int)(bRd.BaseStream.Length - crntStrmPos);

                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Pointer";
                runTVar[ittr].AEUC_Val = MemF_memPtr;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Offset";
                runTVar[ittr].AEUC_Val = crntStrmPos;
                runTVar[ittr].AEUC_Id = (uint)ittr++;
                #endregion
                GenPayloadStruct marshallCopy = new GenPayloadStruct("marshall copy", runTVar);
                #region Create the all-in-one bytestream containing all the OMX structure payloads
                byte[] msgByteStream = marshallCopy.prepareByteStream();
                byte[] nwStream = null;
                if (bRd.BaseStream.Length - crntStrmPos > 1024)
                {
                    nwStream = bRd.ReadBytes(1024);
                    crntStrmPos += 1024;
                }
                else
                {
                    nwStream = bRd.ReadBytes((int)(bRd.BaseStream.Length - crntStrmPos));
                    crntStrmPos += (int)(bRd.BaseStream.Length - crntStrmPos);
                }
                byte[] tpStream = new byte[msgByteStream.Length + nwStream.Length];
                msgByteStream.CopyTo(tpStream, 0);
                nwStream.CopyTo(tpStream, msgByteStream.Length);
                msgByteStream = tpStream;
                #endregion

                //Send the thus formed bytestream message
                atpc.cmcDefinitios.msgSYSMarshalCopy.payloadStruct = null;
                bytestreamTransfer(atpc.cmcDefinitios.msgSYSMarshalCopy.GenerateMessage(msgByteStream));
                MemF_areDoneCopy.WaitOne();
                tmpProgBar.Step();
            }

            OnCompInstUpdate -= new omxCompUpdate(marshallDoneCopyFile);

            atpc.destroyProgBarsDisplay(progDisplay);
            bRd.Close();

            if (OnOperationComplete != null)
                OnOperationComplete();
        }

        Boolean waiting = true;
        void marshallAllocationDoneCopyFile(UCTabPage.ParameterStreamParseResult updateEvent, object data)
        {
            lock (this)
            {
                if (updateEvent == ParameterStreamParseResult.SYS_MARSHAL_ALLOC && waiting)
                {
                    waiting = false;
                    OnCompInstUpdate -= new omxCompUpdate(marshallAllocationDoneCopyFile);

                    if (atpc.cmcDefinitios.msgSYSMarshalCopy != null)
                    {
                        GenMSG tst = (GenMSG)data;

                        if (tst.msgStatus.UID != 0)
                        {
                            MemF_memSz = 0;
                            MemF_memPtr = uint.MaxValue;

                            if (OnOperationComplete != null)
                                OnOperationComplete();

                            return;
                        }

                        uint compId = (UInt32)tst.payloadStruct[0];//Access first item in bytestream that should be the component instance id.
                        uint mhsSize = (UInt32)tst.payloadStruct[1];//Access second item in bytestream that should be the allocation size.
                        uint mhsPtr = (UInt32)tst.payloadStruct[2];//Access third item in bytestream that should be the allocated pointer.

                        MemF_componentId = compId;
                        MemF_memPtr = mhsPtr;
                        MemF_memSz = mhsSize;
                        progDisplay = atpc.initProgBarsDisplay();
                        Thread thrdFCopy = new Thread(new ThreadStart(fileCopyingThread));
                        thrdFCopy.IsBackground = true;
                        thrdFCopy.Start();
                    }
                    else
                    {
                        MessageBox.Show("System marshalling memory copy message not bound!");
                    }
                }
            }
        }

        /// <summary>
        /// Sends memory copy message and load a file to that memory
        /// </summary>
        /// <param name="i_componentId">Component id in which context to allocate the memory</param>
        /// <param name="i_fInf">File to load</param>
        /// <param name="i_memPtr">Marshalled memory pointer</param>
        public void marshallingMemFileLoad(uint i_componentId, FileInfo i_fInf, int i_memPtr)
        {
            MemF_componentId = i_componentId;
            MemF_fInf = i_fInf;
            MemF_memPtr = (uint)i_memPtr;
            if (atpc.cmcDefinitios.msgSYSMarshalCopy != null)
            {
                progDisplay = atpc.initProgBarsDisplay();
                Thread thrdFCopy = new Thread(new ThreadStart(fileCopyingThread));
                thrdFCopy.IsBackground = true;
                thrdFCopy.Start();
            }
            else
            {
                MessageBox.Show("System marshalling memory copy message not bound!");
            }
        }

        void marshallDoneCopyFile(UCTabPage.ParameterStreamParseResult updateEvent, object data)
        {
            if (updateEvent == ParameterStreamParseResult.SYS_MARSHAL_COPY)
            {
                MemF_areDoneCopy.Set();
            }
        }

        /// <summary>
        /// Sends memory free message
        /// </summary>
        /// <param name="componentId">Component id in which context to allocate the memory</param>
        /// <param name="memPtr">Memory pointer to free</param>
        public void marshallingMemFree(uint componentId, int memPtr)
        {
            if (atpc.cmcDefinitios.msgSYSMarshalFree != null)
            {
                #region Prepare marhsalling memory allocation message

                GenPayloadStruct.NewPldItem[] runTVar = new GenPayloadStruct.NewPldItem[4];
                int ittr = 0;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "ComponentId";
                runTVar[ittr].AEUC_Val = componentId;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Size";
                runTVar[ittr].AEUC_Val = 0;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Pointer";
                runTVar[ittr].AEUC_Val = memPtr;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Offset";
                runTVar[ittr].AEUC_Val = 0;
                runTVar[ittr].AEUC_Id = (uint)ittr++;
                #endregion

                GenPayloadStruct marshallAlloc = new GenPayloadStruct("marshall free", runTVar);
                atpc.cmcDefinitios.msgSYSMarshalFree.payloadStruct = null;
                bytestreamTransfer(atpc.cmcDefinitios.msgSYSMarshalFree.GenerateMessage(marshallAlloc.prepareByteStream()));
            }
            else
            {
                MessageBox.Show("System marshalling memory free message not bound!");
            }
        }

        /// <summary>
        /// Sends memory dump message
        /// </summary>
        /// <param name="componentId">Component id in which context to allocate the memory</param>
        /// <param name="memPtr">Memory pointer to free</param>
        /// <param name="memSz">Memory size to free</param>
        public void marshallingMemDump(uint componentId, int memPtr, int memSz)
        {
            if (atpc.cmcDefinitios.msgSYSMarshalDump != null)
            {
                #region Prepare marhsalling memory allocation message

                GenPayloadStruct.NewPldItem[] runTVar = new GenPayloadStruct.NewPldItem[4];
                int ittr = 0;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "ComponentId";
                runTVar[ittr].AEUC_Val = componentId;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Size";
                runTVar[ittr].AEUC_Val = memSz;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Pointer";
                runTVar[ittr].AEUC_Val = memPtr;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Offset";
                runTVar[ittr].AEUC_Val = 0;
                runTVar[ittr].AEUC_Id = (uint)ittr++;
                #endregion

                GenPayloadStruct marshallAlloc = new GenPayloadStruct("marshall dump", runTVar);
                atpc.cmcDefinitios.msgSYSMarshalDump.payloadStruct = null;
                bytestreamTransfer(atpc.cmcDefinitios.msgSYSMarshalDump.GenerateMessage(marshallAlloc.prepareByteStream()));
            }
            else
            {
                MessageBox.Show("System marshalling memory dump message not bound!");
            }
        }

        /// <summary>
        /// Parses DCC config file and generates a file containing all of the specified in the config DCC files
        /// </summary>
        /// <param name="fInf">Configuration file containing all of the required DCC files associated with a sensor</param>
        /// <param name="dccSenId">Requested DCC sensor configuration</param>
        /// <returns>The created file's name that contains all of the DCC configurations</returns>
        public static string preparseDCCfile(FileInfo fInf, string[] dccSenId)
        {
            string preparseFileName = "invalid file";

            if (fInf.Exists)
            {
                StreamReader br = fInf.OpenText();
                string senIdTag = "SENSOR: ";
                string sensorId = "NO SENSOR";

                FileInfo preparsedFile = null;
                BinaryWriter preparseDcc = null;
                for (int i = 0; i < dccSenId.Length; i++)
                {
                    do
                    {
                        sensorId = br.ReadLine();
                        if (sensorId.Length > senIdTag.Length && sensorId.Substring(0, senIdTag.Length) == senIdTag)
                        {
                            string senDCC = sensorId.Substring(senIdTag.Length, sensorId.Length - senIdTag.Length);
                            if (senDCC.Length >= dccSenId[i].Length && senDCC.Substring(0, dccSenId[i].Length) == dccSenId[i])
                            {
                                if (preparsedFile == null || preparseDcc == null)
                                {
                                    preparsedFile = new FileInfo(fInf.FullName.Replace(fInf.Name, "packed_dcc.tmp"));
                                    preparseDcc = new BinaryWriter(preparsedFile.Create());
                                }
                                if (preparsedFile.Exists)
                                {
                                    string dccFile = br.ReadLine();
                                    while (dccFile != null)
                                    {
                                        if (dccFile.Length >= senIdTag.Length && dccFile.Substring(0, senIdTag.Length) == senIdTag)
                                        {
                                            if (dccFile.Substring(senIdTag.Length, dccFile.Length - senIdTag.Length) == dccSenId[i])
                                                dccFile = br.ReadLine();
                                            else
                                                break;
                                        }

                                        if (dccFile != "")
                                        {
                                            FileInfo dccCfg = new FileInfo(dccFile);
                                            if (!dccCfg.Exists)
                                            {
                                                preparseDcc.Close();
                                                br.Close();
                                                return preparseFileName;
                                            }

                                            BinaryReader ddRead = new BinaryReader(dccCfg.OpenRead());
                                            preparseDcc.Write(ddRead.ReadBytes((int)ddRead.BaseStream.Length));
                                            ddRead.Close();
                                        }
                                        dccFile = br.ReadLine();
                                    }
                                    preparseFileName = preparsedFile.FullName;
                                }
                            }
                        }
                    }
                    while (!br.EndOfStream);
                    br.BaseStream.Position = 0;
                }

                br.Close();
                if (preparseDcc != null)
                    preparseDcc.Close();
                return preparseFileName;
            }

            return preparseFileName;
        }

        /// <summary>
        /// Loads a DCC config file, preparses all required DCC files and marshalls them to DUCATI memory
        /// </summary>
        /// <param name="componentId">Component id in which context to allocate the memory</param>
        /// <param name="fInf">File to load</param>
        /// <param name="dccSenId">Requested DCC sensor configuration</param>
        /// <param name="dccURIbuffer">String id of DCC URI Buffer pointer parameter</param>
        public void marshallDCC(uint componentId, FileInfo fInf, string[] dccSenId, string dccURIbuffer)
        {
            if (atpc.cmcDefinitios.msgSYSMarshalAllocType != null)
            {
                if (opHandler == null)
                    opHandler = new OperationComplete(UCTabPage_OnOperationComplete);
                OnOperationComplete += opHandler;
                dccURIinfo = dccURIbuffer;

                #region Prepare marhsalling memory allocation message
                OnCompInstUpdate += new omxCompUpdate(marshallAllocationDoneCopyFile);

                GenPayloadStruct.NewPldItem[] runTVar = new GenPayloadStruct.NewPldItem[2];
                int ittr = 0;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "ComponentId";
                runTVar[ittr].AEUC_Val = componentId;
                runTVar[ittr].AEUC_Id = (uint)ittr++;

                runTVar[ittr] = new GenPayloadStruct.NewPldItem();
                runTVar[ittr].AEUC_DisplayName = "Alloc type";
                runTVar[ittr].AEUC_Val = 5;
                runTVar[ittr].AEUC_Id = (uint)ittr++;
                #endregion

                GenPayloadStruct marshallAllocType = new GenPayloadStruct("marshall alloc type", runTVar);
                atpc.cmcDefinitios.msgSYSMarshalAllocType.payloadStruct = null;
                bytestreamTransfer(atpc.cmcDefinitios.msgSYSMarshalAllocType.GenerateMessage(marshallAllocType.prepareByteStream()));

                marshallingMemAllocFileLoad(componentId, new FileInfo(preparseDCCfile(fInf, dccSenId)));
            }
            else
            {
                MessageBox.Show("System marshalling memory allocation type message not bound!");
            }
        }

        void UCTabPage_OnOperationComplete()
        {
            lock (this)
            {
                waiting = true;
            }
            OnOperationComplete -= opHandler;
            opHandler = null;

            if (MemF_memSz == 0 || MemF_memPtr == uint.MaxValue)
            {
                MessageBox.Show("Transferring DCC data failed!");
                return;
            }

            for (int i = 0; i < atpc.gtpProperties.Count; i++)
            {
                if (atpc.gtpProperties[i].TabName == dccURIinfo)
                {
                    GenPayloadStruct marshallDCCBufPtr = new GenPayloadStruct(dccURIinfo, atpc.gtpProperties[i].GetSettingArray,
                                                                                            atpc.gtpProperties[i].TabRelCompId,
                                                                                            atpc.gtpProperties[i].TabId,
                                                                                            atpc.gtpProperties[i].TabIdExtra);
                    marshallDCCBufPtr[marshallDCCBufPtr["nDCCURIBuffSize"]] = MemF_memSz;
                    marshallDCCBufPtr[marshallDCCBufPtr["nDCCURIBuff"]] = MemF_memPtr;
                    atpc.cmcDefinitios.msgOMXSetCompParam.payloadStruct = null;
                    bytestreamTransfer(atpc.cmcDefinitios.msgOMXSetCompParam.GenerateMessage(marshallDCCBufPtr.prepareByteStream()));
                    return;
                }
            }

            MessageBox.Show("DCC URI buffer pointer parameter structure not specified!");
        }

        void dccUriInfoCollectThread()
        {
            uriEOF = false;
            OnCompInstUpdate += new omxCompUpdate(marshallDCCCollectURIInfosDone);
            GenPayloadStruct marshallDCCURIInfo = null;
            int nPortIndx = 0;
            
            for (int i = 0; i < atpc.gtpProperties.Count; i++)
            {
                if (atpc.gtpProperties[i].TabName == dccURIinfo)
                {
                    dccURIinfoId = atpc.gtpProperties[i].TabId;
                    marshallDCCURIInfo = new GenPayloadStruct(dccURIinfo, atpc.gtpProperties[i].GetSettingArray,
                                                                                atpc.gtpProperties[i].TabRelCompId,
                                                                                atpc.gtpProperties[i].TabId,
                                                                                atpc.gtpProperties[i].TabIdExtra);
                    break;
                }
            }

            DCCURIInfoStruct = marshallDCCURIInfo;
            if (marshallDCCURIInfo == null)
            {
                MessageBox.Show("DCC URI Info request parameter structure not specified!");
                OnCompInstUpdate -= new omxCompUpdate(marshallDCCCollectURIInfosDone);
                return;
            }

            while (!uriEOF)
            {
                marshallDCCURIInfo[marshallDCCURIInfo["nPortIndex"]] = nPortIndx++;
                atpc.cmcDefinitios.msgOMXGetCompParam.payloadStruct = null;
                bytestreamTransfer(atpc.cmcDefinitios.msgOMXGetCompParam.GenerateMessage(marshallDCCURIInfo.prepareByteStream()));
                MemF_areDoneCopy.WaitOne();
            }

            OnCompInstUpdate -= new omxCompUpdate(marshallDCCCollectURIInfosDone);

            if (sensors.Count == 0)
                sensors.Add("NO SENSOR");

            if (OnDCCURICollected != null)
                OnDCCURICollected(sensors.ToArray());
        }

        /// <summary>
        /// Creates an array of strings representing the available sensor models
        /// </summary>
        /// <param name="componentId">OMX Component to be queried</param>
        /// <param name="idccURIinfo">String id of DCC URI Info request parameter</param>
        public void marshallDCCCollectURIInfos(uint componentId, string idccURIinfo)
        {
            sensors = new List<string>();
            dccURIinfo = idccURIinfo;

            Thread dccUriCollect = new Thread(new ThreadStart(dccUriInfoCollectThread));
            dccUriCollect.IsBackground = true;
            dccUriCollect.Start();
        }

        void marshallDCCCollectURIInfosDone(UCTabPage.ParameterStreamParseResult updateEvent, object data)
        {
            if (updateEvent == ParameterStreamParseResult.PARSE_OK)
            {
                GenMSG pldMsg = (GenMSG)data;
                if (pldMsg != null && (uint)pldMsg.payloadStruct[1] == dccURIinfoId)
                {
                    if (pldMsg.msgStatus.UID == 0)
                    {
                        sensors.Add(pldMsg.payloadStruct.getParamStringVal(pldMsg.payloadStruct["sDCCURI"]));
                    }
                    else
                        uriEOF = true;

                    MemF_areDoneCopy.Set();
                }
            }
        }

        #endregion

        /// <summary>
        /// Get handgle for component instance method
        /// </summary>
        public void GetComponentInstanceHandle(string compName)
        {
            if (atpc.cmcDefinitios.msgOMXGetCompInstance != null)
            {
                GenMSGId tstId = new GenMSGId();
                tstId.UID = atpc.cmcDefinitios.msgOMXGetCompInstance.msgId.UID;

                GenMSGStatus tstStatus = new GenMSGStatus();
                tstStatus.UID = atpc.cmcDefinitios.msgOMXGetCompInstance.msgStatus.UID;

                GenMSG tst = new GenMSG(atpc, tstId, tstStatus, null, false);
                tst.payloadStruct = new GenPayloadStruct("", null);
                tst.payloadStruct.AddPayloadStringItem(compName);

                bytestreamTransfer(tst.GenerateMessage(null));
            }
            else
                MessageBox.Show("OMX Get component instance handle message not specified!");
        }
        /// <summary>
        /// Get OMX component ports
        /// </summary>
        public void GetComponentInstancePorts(uint compId)
        {
            if (atpc.cmcDefinitios.msgOMXGetCompPorts != null)
            {
                GenMSGId tstId = new GenMSGId();
                tstId.UID = atpc.cmcDefinitios.msgOMXGetCompPorts.msgId.UID;

                GenMSGStatus tstStatus = new GenMSGStatus();
                tstStatus.UID = atpc.cmcDefinitios.msgOMXGetCompPorts.msgStatus.UID;

                GenMSG tst = new GenMSG(atpc, tstId, tstStatus, null, false);
                tst.payloadStruct = new GenPayloadStruct("", null);

                IAEUCSetting[] runTVar = new IAEUCSetting[1];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "Component id";
                runTVar[0].AEUC_Id = 0;

                tst.payloadStruct.SetPayloadItems(runTVar);

                tst.payloadStruct[0] = compId;

                bytestreamTransfer(tst.GenerateMessage(null));
            }
            else
                MessageBox.Show("OMX Get component ports message not specified!");
        }
        /// <summary>
        /// Allocate OMX component port buffers
        /// </summary>
        public void AllocComponentPortBuffs(uint compId, uint portN)
        {
            if (atpc.cmcDefinitios.msgOMXAllocPortBuffs != null)
            {
                GenMSGId tstId = new GenMSGId();
                tstId.UID = atpc.cmcDefinitios.msgOMXAllocPortBuffs.msgId.UID;

                GenMSGStatus tstStatus = new GenMSGStatus();
                tstStatus.UID = atpc.cmcDefinitios.msgOMXAllocPortBuffs.msgStatus.UID;

                GenMSG tst = new GenMSG(atpc, tstId, tstStatus, null, false);
                tst.payloadStruct = new GenPayloadStruct("", null);

                IAEUCSetting[] runTVar = new IAEUCSetting[2];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "Component id";
                runTVar[0].AEUC_Id = 0;
                runTVar[1] = new GenPayloadStruct.NewPldItem();
                runTVar[1].AEUC_DisplayName = "Port number";
                runTVar[1].AEUC_Id = 1;

                tst.payloadStruct.SetPayloadItems(runTVar);

                tst.payloadStruct[0] = compId;
                tst.payloadStruct[1] = portN;

                bytestreamTransfer(tst.GenerateMessage(null));
            }
            else
                MessageBox.Show("OMX Allocate component port buffers message not specified!");
        }
        /// <summary>
        /// Link OMX components ports
        /// </summary>
        public void LinkComponentPorts(uint comp1_Id, uint comp1_portN, uint comp2_Id, uint comp2_portN)
        {
            if (atpc.cmcDefinitios.msgOMXLinkCompPorts != null)
            {
                GenMSGId tstId = new GenMSGId();
                tstId.UID = atpc.cmcDefinitios.msgOMXLinkCompPorts.msgId.UID;

                GenMSGStatus tstStatus = new GenMSGStatus();
                tstStatus.UID = atpc.cmcDefinitios.msgOMXLinkCompPorts.msgStatus.UID;

                GenMSG tst = new GenMSG(atpc, tstId, tstStatus, null, false);
                tst.payloadStruct = new GenPayloadStruct("", null);

                IAEUCSetting[] runTVar = new IAEUCSetting[4];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "Component 1 id";
                runTVar[0].AEUC_Id = 0;
                runTVar[1] = new GenPayloadStruct.NewPldItem();
                runTVar[1].AEUC_DisplayName = "Component 1 port number";
                runTVar[1].AEUC_Id = 1;
                runTVar[2] = new GenPayloadStruct.NewPldItem();
                runTVar[2].AEUC_DisplayName = "Component 2 id";
                runTVar[2].AEUC_Id = 2;
                runTVar[3] = new GenPayloadStruct.NewPldItem();
                runTVar[3].AEUC_DisplayName = "Component 2 port number";
                runTVar[3].AEUC_Id = 3;

                tst.payloadStruct.SetPayloadItems(runTVar);

                tst.payloadStruct[0] = comp1_Id;
                tst.payloadStruct[1] = comp1_portN;
                tst.payloadStruct[2] = comp2_Id;
                tst.payloadStruct[3] = comp2_portN;

                bytestreamTransfer(tst.GenerateMessage(null));
            }
            else
                MessageBox.Show("OMX Link components ports message not specified!");
        }
        /// <summary>
        /// Send component set state command
        /// </summary>
        /// <param name="compID">Component id</param>
        /// <param name="compCmd">Command</param>
        /// <param name="cmdParam">Command parameter</param>
        /// <param name="cmdData">Command data</param>
        public void SendCompCommand(uint compID, uint compCmd, uint cmdParam, uint cmdData)
        {
            if (atpc.cmcDefinitios.msgOMXCompCmds != null)
            {
                GenMSGId tstId = new GenMSGId();
                tstId.UID = atpc.cmcDefinitios.msgOMXCompCmds.msgId.UID;

                GenMSGStatus tstStatus = new GenMSGStatus();
                tstStatus.UID = atpc.cmcDefinitios.msgOMXCompCmds.msgStatus.UID;

                GenMSG tst = new GenMSG(atpc, tstId, tstStatus, null, false);
                tst.payloadStruct = new GenPayloadStruct("", null);

                IAEUCSetting[] runTVar = new IAEUCSetting[4];
                runTVar[0] = new GenPayloadStruct.NewPldItem();
                runTVar[0].AEUC_DisplayName = "Component id";
                runTVar[0].AEUC_Id = 0;
                runTVar[1] = new GenPayloadStruct.NewPldItem();
                runTVar[1].AEUC_DisplayName = "Command";
                runTVar[1].AEUC_Id = 1;
                runTVar[2] = new GenPayloadStruct.NewPldItem();
                runTVar[2].AEUC_DisplayName = "Param";
                runTVar[2].AEUC_Id = 2;
                runTVar[3] = new GenPayloadStruct.NewPldItem();
                runTVar[3].AEUC_DisplayName = "Command data";
                runTVar[3].AEUC_Id = 3;

                tst.payloadStruct.SetPayloadItems(runTVar);

                tst.payloadStruct[0] = compID;
                tst.payloadStruct[1] = compCmd;
                tst.payloadStruct[2] = cmdParam;
                tst.payloadStruct[3] = cmdData;

                bytestreamTransfer(tst.GenerateMessage(null));
            }
            else
                MessageBox.Show("OMX component command message not specified!");
        }

        void bytestreamTransfer(byte[] bytestream)
        {
            if (commLink != null)
                commLink.msgSendData(bytestream);
        }
        #endregion
        #endregion

        #region Connection and connection status reporting
        /// <summary>
        /// Creates a communication link object based on user media selection.
        /// </summary>
        public void AttachCommLinkChannel(CommLink.CommLink iCommChannel)
        {
            commLink = iCommChannel;
            if (commLink != null)
                commLink.OnMessageReceived += new CommLink.CommLink.MessageReceived(commLink_OnMessageReceived);
        }
        /// <summary>
        /// Returns the current active communication media object
        /// </summary>
        /// <returns></returns>
        public CommLink.CommLink GetCommObject()
        {
            return commLink;
        }
        #endregion
    }
}
